package gin

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/net/websocket"
	"net"
	"net/http"
)

func HandleWebsocket(conn *websocket.Conn) {
	var err error
	var reply string
	for {
		for i := 0; i < 5; i++ {
			websocket.Message.Send(conn, "hello")
		}

		if err = websocket.Message.Receive(conn, &reply); err != nil {
			fmt.Print(err)
			break
		}
		fmt.Println("from client:" + reply)
	}
}

func GinServer() {
	engine := gin.Default()
	engine.GET("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{
			"message": "hello",
		})
	})
	engine.StaticFS("/static", http.Dir("/Users/myselffan/projects-test/go/go-demo/web/websocket/static"))
	/**
	http server使用gin
	*/
	http.Handle("/", engine)

	/**
	websocket  使用官方websocket
	*/
	http.Handle("/push", websocket.Handler(HandleWebsocket))

	listener, _ := net.Listen("tcp", ":9000")
	http.Serve(listener, nil)
}
